<?php


namespace Base;


use EasySwoole\Component\Di;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use Lib\Log;

class BaseController extends Controller
{
    public $params = [];
    public $uid = 0;
    public $userinfo = [];
    public $needLogin = false;

    public function request(): Request
    {
        return parent::request();
    }

    public function response(): Response
    {
        return parent::response();
    }

    protected function onRequest(?string $action): ?bool
    {
        $middlewares = Di::getInstance()->get('middlewares') ?? [];
        foreach ($middlewares as $middleware) {
            $middleware::handle($this);
        }
        return parent::onRequest($action);
    }

    protected function returnJson($data = [], $msg = '', $code = 200)
    {
        if (!$this->response()->isEndResponse()) {
            $return = [
                'code' => $code,
                'result' => $data,
                'msg' => $msg
            ];

            $this->response()->withAddedHeader('Content-Type', 'application/json; charset=utf-8');
            $this->response()->withAddedHeader('Access-Control-Allow-Credentials', 'true');
            $this->response()->withAddedHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Access-Token,user-id,Request-Url,Source,Longitude,Latitude,Wechat-Openid,Authorization');
            $this->response()->withAddedHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
            $this->response()->withAddedHeader('Content-Type', 'application/json; charset=utf-8');
            $this->response()->withStatus(200);
            $this->response()->write(json_encode($return, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
            return true;
        } else {
            trigger_error('response has end');
            return false;
        }
    }

    protected function onException(\Throwable $throwable): void
    {
        echo $throwable->getFile() . ' line:' . $throwable->getLine() . PHP_EOL . $throwable->getMessage() . PHP_EOL;
        Log::error(json_encode($throwable->getTrace()));
        $this->returnJson([], $throwable->getMessage(), $throwable->getCode());
    }
}
